package com.fnzx.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fnzx.common.enums.ResponseStatusEnum;
import com.fnzx.common.exception.MailExistException;
import com.fnzx.common.exception.PhoneExistException;
import com.fnzx.entity.UserEntity;
import com.fnzx.entity.vo.UserInfoVo;
import com.fnzx.service.UserService;
import com.fnzx.util.PageUtils;
import com.fnzx.util.R;
import com.fnzx.util.common.ExcelUtil;
import com.fnzx.util.common.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;


/**
 * 
 *
 * @author Wang Zhifu
 * @date 2021-10-23 22:20:01
 */
@Api(tags = "用户模块")
@RestController
@RequestMapping("iot/user")
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation(value = "登录接口",notes = "账号登录示例:{\"username\":\"iot\",\"password\":\"iot666\"}，用户登录会生成token（包含用户id和userType）")
    @PostMapping("/login")
    public R login(@RequestBody HashMap<String,String> map, HttpServletResponse response){
        UserEntity user = userService.login(map);
        //jwt的负载信息，增添token到请求头
        return putToken(user,response);
    }

    @ApiOperation(value = "超级管理员的登录接口",notes = "账号登录示例:notes = \"账号登录示例:{\"username\":\"admin\",\"password\":\"admin\"}")
    @PostMapping("/admin/login")
    public R adminLogin(@RequestBody HashMap<String,String> map, HttpServletResponse response){
        UserEntity user = userService.adminLogin(map);
        //jwt的负载信息，增添token到请求头
        return putToken(user,response);
    }

    @ApiOperation(value = "注册账号")
    @PostMapping("/register")
    public R register(@RequestBody UserEntity userEntity){
        try {
            userService.rigister(userEntity);
        } catch (PhoneExistException e) {
            return R.error(ResponseStatusEnum.PHONE_EXIST.getStatus(), e.getMessage());
        } catch (MailExistException e) {
            return R.error(ResponseStatusEnum.MAIL_EXIST.getStatus(), e.getMessage());
        }
        return R.ok();
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页",paramType = "query",required = true,dataType = "String"),
            @ApiImplicitParam(name = "limit",value = "每页记录数",paramType = "query",required = true,dataType = "String")
    })
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userService.getAllUserInfoPage(params);
        return R.ok().put("page",page);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页",paramType = "query",required = true,dataType = "String"),
            @ApiImplicitParam(name = "limit",value = "每页记录数",paramType = "query",required = true,dataType = "String")
    })
    @ApiOperation("分页获取所有管理员用户")
    @GetMapping("/admin/list")
    public R listAdmin(@RequestParam Map<String, Object> params){
        PageUtils page = userService.listAdmin(params);
        return R.ok().put("page",page);
    }

    @ApiOperation("导出管理员用户")
    @GetMapping("/admin/export")
    public void exportAdmin(HttpServletResponse response){
        List<UserEntity> list = userService.list(new QueryWrapper<UserEntity>().eq("user_type", 9));
        ExcelUtil<UserEntity> excelUtil = new ExcelUtil<>();
        excelUtil.export("管理员用户",list,response);
    }


    @ApiOperation(value = "根据用户id返回用户的具体信息")
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		UserInfoVo userInfo = userService.getUserInfoById(id);
        return R.ok().put("userInfo", userInfo);
    }

    @ApiOperation(value = "删除")
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		userService.delete(Arrays.asList(ids));
        return R.ok();
    }

    @GetMapping("/exist")
    @ApiOperation(value = "用户注册用户名时，检查用户名可用")
    public R exist(@RequestParam String username){
        UserEntity one = userService.getOne(new QueryWrapper<UserEntity>().eq("username", username));
        if (one==null){
            return R.ok("用户名可用");
        }else{
            return R.error("sorry，用户名已存在");
        }
    }

    @ApiOperation(value = "更改用户禁用状态 id-->用户id,status-->0表示解除禁用，1表示禁用该用户")
    @GetMapping("/prohibit")
    public R prohibit(@RequestParam Long id,@RequestParam Integer status){
        if (status!=0 && status!=1){
            return R.error(ResponseStatusEnum.PARAM_ERROR.getStatus(),ResponseStatusEnum.PARAM_ERROR.getMsg());
        }
        userService.prohibit(id,status);
        return R.ok();
    }

    @ApiOperation("根据用户名查找《管理员用户》")
    @GetMapping("/query")
    public R queryAdminUser(@RequestParam String username){
        List<UserEntity> list = userService.list(
                new QueryWrapper<UserEntity>()
                        .eq("user_type", 9)
                        .like(!ObjectUtils.isEmpty(username), "username", username)
        );
        return R.ok().put("data",list);
    }

//====================非接口方法==========================

    /**
     * 给用户登录后的请求头放token并返回R
     * @param user 用户信息-->token的负载信息
     * @param response 响应体
     */
    public R putToken(UserEntity user, HttpServletResponse response){

        if (user!=null) {
            if (user.getStatus()==-1){
                return R.error(ResponseStatusEnum.USER_PROHIBIT.getStatus(),ResponseStatusEnum.USER_PROHIBIT.getMsg());
            }
            //jwt的负载信息，增添token到请求头
            HashMap<String, String> payload = new HashMap<>();
            payload.put("id",user.getId().toString());
            payload.put("userType",user.getUserType().toString());
            response.setHeader("token",JwtUtil.createToken(payload));
            return R.ok().put("user", user);
        }
        return R.error(ResponseStatusEnum.USER_NOTFOUND.getStatus(), ResponseStatusEnum.USER_NOTFOUND.getMsg());
    }
}
